<template>

  <div>
    <div class="w">
      <!-- 标题 -->
      <div class="title-area">
        <span>
          基本信息
        </span>
      </div>

      <!-- 主体内容显示区 -->
      <div class="content-area">

        <!-- 查询表单区 -->
        <div>
          <Form style="margin-right: 50px;"
            name="form" 
            ref="formRef" 
            :labelCol="{ span: 9 }" 
            :wrapperCol="{ span: 15 }" 
            :initialValues="form"
            @finish="formFinish">

            <Row>
              <Col :span="8">
                <FormItem name="solutionNumber" label="方案编码">
                  <Input style="width: 100%" disabled />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem name="solutionName" label="方案名称" :rules="formRules.solutionName">
                  <Input placeholder="请输入方案名称" style="width: 100%" />
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem name="solutionType" label="方案类型" :rules="formRules.solutionType" style="position: relative;" class="solutionTypePopupContainer">
                  <Select placeholder="请选择方案类型" style="width: 100%" :getPopupContainer="getSolutionTypePopupContainer">
                    <Option v-for="type in refData.solutionTypes" :key="type.value" :value="type.value" :label="type.label" />
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col :span="8">
                <FormItem name="appType" label="应用类型" :rules="formRules.appType" style="position: relative;" class="appTypePopupContainer">
                  <Select placeholder="请选择应用类型" style="width: 100%" :getPopupContainer="getAppTypePopupContainer">
                    <Option v-for="type in refData.appTypes" :key="type.value" :value="type.value" :label="type.label" />
                  </Select>
                </FormItem>
              </Col>
              <Col :span="16">
                <FormItem name="produceId" label="产品" :rules="formRules.produceId" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }" style="position: relative;" class="produceIdPopupContainer">
                  <Cascader style="width: 100%" placeholder="请选择厂商产品" :options="refData.firmsList" :getPopupContainer="getProduceIdPopupContainer" />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col :span="24">
                <FormItem name="remark" label="解决方案说明" :rules="formRules.remark" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                  <TextArea placeholder="请输入解决方案说明" style="width: 100%; height: 100px;" />
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
    </div>

    <div class="w" style="margin-top: 5px;">
      <!-- 标题 -->
      <div class="title-area">
        <span>
          步骤管理
        </span>
      </div>

      <!-- 操作按钮 -->
      <Button type="primary" style="position: absolute; top: 2px; right: 25px;" @click="addNewSolutionStep">
        <Icon name="add-new" style="margin-top: 4px;" /> 新增步骤
      </Button>

      <!-- 主体内容显示区 -->
      <div class="content-area">
        <Table
          :columns="tableColumns"
          :dataSource="tableData"
          :bordered="false"
          :rowKey="(record) => record.stepName"
          :pagination="false">

          <template #render="render">
            <div v-if="render.dataIndex == 'id'">
              {{ render.index + 1 }}
            </div>
            <div v-else-if="render.dataIndex == 'stepName'">
              <Input placeholder="请输入步骤名称" style="width: 100%;" v-model="render.record.stepName" />
            </div>
            <div v-else-if="render.dataIndex == 'solutionStepFile'">
                <Upload v-model="render.record.solutionStepFile" uploadText="选取文件" :fileType="['doc', 'docx', 'pdf']" :fileSize="100" :limit="1"></Upload>
            </div>
            <div v-else-if="render.dataIndex == 'remark'">
              <Input placeholder="请输入说明" style="width: 100%;" v-model="render.record.remark" />
            </div>
            <div v-else-if="render.dataIndex == 'stepOrder'">
              <InputNumber :min="1" :max="99" defaultValue="0" v-model="render.record.stepOrder" />
            </div>
            <div v-else-if="render.dataIndex == 'operation'">
              <a href="#" @click="moveSolutionStep(render.index, true)" :disabled="render.index <= 0"><Icon name="arrow-up" style="margin-top: 4px;" /></a>
              <span> </span>
              <a href="#" @click="moveSolutionStep(render.index, false)" :disabled="render.index >= tableData.length - 1"><Icon name="arrow-down" style="margin-top: 4px;" /></a>
              <Button type="link" size="sm" @click="removeSolutionStep(render.index)">删除</Button>
            </div>
          </template>
        </Table>

        <Row style="margin-top: 20px;">
          <Col :span="12" :offset="9">
            <Button style="width: 100px;" type="primary" @click="formValidate">提 交</Button>
            <Button style="width: 100px; margin-left: 20px;" @click="formCancel">取 消</Button>
          </Col>
        </Row>
      </div>
    </div>

    <!-- 提交确认框 -->
    <Modal title="提交确认" v-model="isModalVisible" @ok="formSubmit" @cancel="isModalVisible = false" centered>
      <p>即将提交解决方案信息，是否确认？</p>
    </Modal>
  </div>
</template>

<script>
import * as ruoyi from '@/utils/ruoyi'
import { Message } from '@uni/vue';
import { addSolution, updateSolution } from "@/api/dosolution/solution";
import Upload from '@/components/upload'
export default {
  name: "app",
  components: {
    Upload
  },
  props: {
    solutionId: {
      type: Number,
      default: 0
    },
    currRow: {
      default: () => {}
    },
    refData: {
      default: () => {}
    }
  },
  data: function () {
    const validateSolutionType = (rule, value) => {
      let type = this.refData.solutionTypes.find(type => type.value == value);
      if (type) return Promise.resolve();
      else return Promise.reject("请选择方案类型");
    };
    const validateAppType = (rule, value) => {
      let type = this.refData.appTypes.find(type => type.value == value);
      if (type) return Promise.resolve();
      else return Promise.reject("请选择应用类型");
    };
    const validateProduceId = (rule, value) => {
      let produce = this.refData.producesList.find(produce => produce.produceId == value[1]);
      if (produce) return Promise.resolve();
      else return Promise.reject("请选择有效的厂商产品");
    };
    return {
      tableColumns: [
        {"title":"序号", "dataIndex":"id", "key":"id","align":"center", width: 50},
        {"title":"步骤名称", "dataIndex":"stepName", "key":"stepName", width: 180},
        {"title":"步骤附件", "dataIndex":"solutionStepFile", "key":"solutionStepFile","align":"center"},
        {"title":"步骤说明", "dataIndex":"remark", "key":"remark"},
        {"title":"步骤排序", "dataIndex":"stepOrder", "key":"stepOrder", width: 80},
        {"title":"操作", "dataIndex":"operation", "key":"operation","align":"center", width: 90},
      ],
      tableData: [],
      form: {
        solutionNumber: this.solutionId ? this.currRow.solutionNumber : `S${this.getCurrentTime()}`,
        solutionName: this.currRow.solutionName,
        solutionType: `${this.currRow.solutionType ? this.currRow.solutionType : ''}`,
        appType: `${!isNaN(this.currRow.appType) ? this.currRow.appType : ''}`,
        produceId: this.solutionId == 0 ? [] : [
          this.refData.producesList.find(produce => produce.produceId == this.currRow.produceId).firmId,
          this.currRow.produceId
        ],
        remark: this.currRow.remark,
        solutionStepList: []
      },
      formRules: {
        solutionName: [
          { required: true, message: '请输入方案名称' },
        ],
        solutionType: [
          // { required: true, message: '请选择方案类型' },
          { required: true, validator: validateSolutionType },
        ],
        appType: [
          // { required: true, message: '请选择应用类型' },
          { required: true, validator: validateAppType },
        ],
        produceId: [
          // { required: true, message: '请选择厂商产品' },
          { required: true, validator: validateProduceId },
        ],
        remark: [
          { required: true, message: '请输入说明信息' },
        ]
      },
      isModalVisible: false
    }
  },
  mounted: function () {
    // console.log("mounted solutionId: ", this.solutionId);
    // console.log("mounted currRow: ", this.currRow);
    // console.log("mounted refData: ", this.refData);

    if (this.solutionId !== 0) {
      this.form = this.refData.solutionDetail;
      this.tableData = this.refData.solutionDetail.solutionStepList;
    }
  },
  methods: {
    getSolutionTypePopupContainer: function () {
      return document.querySelector('.solutionTypePopupContainer');
    },
    getAppTypePopupContainer: function () {
      return document.querySelector('.appTypePopupContainer');
    },
    getProduceIdPopupContainer: function () {
      return document.querySelector('.produceIdPopupContainer');
    },
    formValidate: function () {
      this.$refs.formRef.submit();
    },
    formCancel: function () {
      // this.$refs.formRef.reset();
      this.handleCancel();
    },
    formFinish: function (formValues) {
      this.form = formValues;
      // this.isModalVisible = true;
      this.formSubmit();
    },
    formSubmit: async function () {
      // 公共属性
      this.form.createBy = this.$store.state.user.name;
      this.form.createTime = ruoyi.parseTime(Date.now());
      this.form.updateBy = this.$store.state.user.name;
      this.form.updateTime = ruoyi.parseTime(Date.now());

      // 提交表单请求
      this.isModalVisible = false;
      let reqForm = JSON.parse(JSON.stringify(this.form));
      reqForm.produceId = this.form.produceId[1];
      reqForm.solutionStepList = this.tableData;
      // console.log("reqForm: ", reqForm);

      if (this.solutionId) {
        // 修改
        reqForm.solutionId = this.solutionId;
        const rs = await updateSolution(reqForm);
        if (rs.code !== 200) return Message.error({ text: '修改解决方案失败：' + rs.msg });
        Message.success({ text: '修改解决方案完成' });
        this.handleCancel();

      } else {
        // 新增
        const rs = await addSolution(reqForm);
        if (rs.code !== 200) return Message.error({ text: '新增解决方案失败：' + rs.msg });
        Message.success({ text: '新增解决方案完成' });
        this.handleCancel();
      }
    },
    addNewSolutionStep: function () {
      this.tableData.push({
        stepName: '',
        solutionStepFile: '',
        remark: '',
        stepOrder: '1'
      });
    },
    moveSolutionStep: function (index, isMoveUp) {
      let finalIndex = isMoveUp ? index - 1 : index + 1;
      let rowFrom = JSON.parse(JSON.stringify(this.tableData[index]));
      let rowTo = JSON.parse(JSON.stringify(this.tableData[finalIndex]));

      this.$set(this.tableData, index, rowTo);
      this.$set(this.tableData, finalIndex, rowFrom);
    },
    removeSolutionStep: function (index) {
      this.tableData.splice(index, 1);
      // console.log('removeSolutionStep: ', this.tableData);
    },
    handleCancel: function () {
      this.$emit('handleCancel');
    }
  }
}
</script>

<style scoped>
  .w {
    /* height: 100%; */
    position: relative;
    background-color: #F9FAFB;
  }

  /* 标题 */
  .title-area {
    height: 36px;
    background-color: #E9EBF0;
  }
  .title-area span {
    display: inline-block;
    font-weight: 500;
    line-height: 36px;
    margin-left: 15px;
  }

  /* 主体内容显示区 */
  .content-area {
    /* background-color: lightblue; */
    height: 100%;
    margin-top: 15px;
    margin-left: 25px;
    margin-right: 25px;
    padding-bottom: 15px;
  }

  .uni-divider {
    margin: 0;
  }

  /* 按钮区 */
  .button-area {
    margin-top: 15px;
    /* background-color: lightcyan; */
  }
  .button-area svg {
    margin-top: 3px;
    margin-right: 5px;
  }

  /* 列表区 */
</style>

